<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body > <!--onmousemove="moveMouse(event)"-->
<div class="one" id="div_id"></div>
</body>
<script>
    var pos=0;
    var d1=document.getElementsByClassName('one')[0];//getElementsByClassName拿到的结果是个数组
    //1.获取元素当前位置和鼠标当前位置
    //2.元素添加鼠标按下和鼠标移动事件
    //3.移动以后获取鼠标的目标位置
    //4.元素目标位置=元素原始位置+(鼠标目标位置-鼠标原来位置)
    var mouseStartX;//鼠标当前位置X
    var mouseStartY;//鼠标当前位置Y
    var eleStartX;//元素当前位置X
    var eleStartY;//元素当前位置Y
    d1.addEventListener('mousedown',start,false);

    function over() {
        console.log("mouseover");
        d1.removeEventListener('mousemove',move);
        d1.removeEventListener('mouseup',end);
    }

    function start(event) {
        var e= event || window.event;
        //获取鼠标位置
        mouseStartX=e.pageX;
        mouseStartY=e.pageY;
        //获取元素位置
        let cse = document.defaultView.getComputedStyle(d1,null)['transform'];
        if(cse==='none'){
            //第一次为null
            d1.style.transform='translate(0,0)'
        }else {
            var poss=(cse.substring(cse.lastIndexOf('(')+1,cse.lastIndexOf(')'))).split(',');
            eleStartX=parseInt(poss[4]);
            eleStartY=parseInt(poss[5]);
            //console.log(eleStartX,eleStartY)
        }
        d1.addEventListener('mousemove',move,false);
        d1.addEventListener('mouseup',end,false);
        //d1.addEventListener('mouseover',over,false);
    }

    function move() {
        //console.log("mousemove");
        var e= event || window.event;
        var currentMouseX=e.pageX;
        var currentMouseY=e.pageY;
        var diffX=currentMouseX-mouseStartX;
        var diffY=currentMouseY-mouseStartY;
        var moveX=eleStartX+diffX;
        var moveY=eleStartY+diffY;
        console.log(moveX,moveY);
        d1.style.transform='translate('+moveX+'px,'+moveY+'px)';
    }

    function end() {
        console.log("mouseup");
        d1.removeEventListener('mousemove',move);
        d1.removeEventListener('mouseup',end);
    }

</script>

<style>
    div{
        width: 50px;
        height: 50px;
        background-color: orange;
        text-align: center;
        position: relative;
        line-height: 50px;/*行高*/
        margin: 5px;
    }
</style>
</html>